<?php
/**
 * OA工作汇报记录模型
 */

declare (strict_types = 1);

namespace app\model\oa;

use think\Model;

class WorkRecord extends Model
{
    // 设置表名
    protected $name = 'work_record';
    
    // 设置主键
    protected $pk = 'id';
    
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = true;
    
    // 定义时间戳字段名
    protected $createTime = 'send_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = 'delete_time';
    
    // 设置字段信息
    protected $schema = [
        'id'           => 'int',
        'work_id'      => 'int',
        'from_uid'     => 'int',
        'to_uid'       => 'int',
        'send_time'    => 'int',
        'read_time'    => 'int',
        'create_time'  => 'int',
        'update_time'  => 'int',
        'delete_time'  => 'int',
    ];

    /**
     * 关联工作汇报
     */
    public function work()
    {
        return $this->belongsTo(Work::class, 'work_id', 'id');
    }

    /**
     * 关联发送人
     */
    public function fromUser()
    {
        return $this->belongsTo(\app\model\admin\User::class, 'from_uid', 'id');
    }

    /**
     * 关联接收人
     */
    public function toUser()
    {
        return $this->belongsTo(\app\model\admin\User::class, 'to_uid', 'id');
    }

    /**
     * 标记为已读
     */
    public function markAsRead(int $id, int $userId): bool
    {
        return $this->where('id', $id)
                   ->where('to_uid', $userId)
                   ->where('read_time', 0)
                   ->update(['read_time' => time()]);
    }

    /**
     * 获取未读数量
     */
    public function getUnreadCount(int $userId): int
    {
        return $this->where('to_uid', $userId)
                   ->where('read_time', 0)
                   ->where('delete_time', 0)
                   ->count();
    }

    /**
     * 批量标记为已读
     */
    public function markAllAsRead(int $userId): int
    {
        return $this->where('to_uid', $userId)
                   ->where('read_time', 0)
                   ->where('delete_time', 0)
                   ->update(['read_time' => time()]);
    }

    /**
     * 获取接收的工作汇报列表（带关联数据）
     */
    public function getReceiveListWithRelations(int $userId, array $params = [], int $page = 1, int $limit = 10): array
    {
        $query = $this->with(['work', 'fromUser'])
                     ->where('to_uid', $userId)
                     ->where('delete_time', 0);

        // 按阅读状态筛选
        if (isset($params['read_status']) && $params['read_status'] !== '') {
            if ($params['read_status'] == 1) {
                $query->where('read_time', 0);
            } else {
                $query->where('read_time', '>', 0);
            }
        }

        // 按工作类型筛选
        if (!empty($params['types'])) {
            $query->whereHas('work', function($q) use ($params) {
                $q->where('types', $params['types']);
            });
        }

        // 按时间检索
        if (!empty($params['date_range'])) {
            $dateRange = explode('~', $params['date_range']);
            $query->whereBetween('send_time', [
                strtotime(urldecode($dateRange[0])), 
                strtotime(urldecode($dateRange[1] . ' 23:59:59'))
            ]);
        }

        $total = $query->count();

        $list = $query->order('send_time', 'desc')
                     ->page($page, $limit)
                     ->select()
                     ->toArray();

        return [
            'list' => $list,
            'total' => $total,
            'page' => $page,
            'limit' => $limit
        ];
    }
}